package com.rk.hosp.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.rk.cmn.client.DictFeignClient;
import com.rk.hosp.model.hosp.Hospital;
import com.rk.hosp.repository.HospitalRepository;
import com.rk.hosp.service.DepartmentService;
import com.rk.hosp.service.HospitalService;
import com.rk.hosp.vo.hosp.HospitalQueryVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author :Rk.
 * @date : 2022/11/9
 */
@Slf4j
@Service
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;


    /**
     * 保存或修改
     *
     * @param paramMap
     */
    @Override
    public void saveOrUpdate(Map<String, Object> paramMap) {

        //把map转换为对象
        String mapString = JSONObject.toJSONString(paramMap);
        log.info(mapString);

        Hospital hospital = JSONObject.parseObject(mapString,Hospital.class);


        //判断  mongodb中是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist= hospitalRepository.getHospitalByHoscode(hoscode);

        //如果存在进行修改 不存在则添加
        if(hospitalExist!=null){
            hospital.setId(hospitalExist.getId());
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            log.info("===================修改=======================");
            hospitalRepository.save(hospital);
        }else {
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            log.info("===================添加=======================");
            hospitalRepository.save(hospital);
        }

    }

    /**
     * 通过医院编码获取医院信息
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 查询医院信息
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //通过createTime降序
        Sort sort=Sort.by(Sort.Direction.ASC,"createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);


        //创建匹配器，即如何使用查询条件 //构建对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                //改变默认字符串匹配方式：模糊查询
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                //改变默认大小写忽略方式：忽略大小写
                .withIgnoreCase(true);

        //创建实例   传入条件和适配器
        Example<Hospital> example = Example.of(hospital, matcher);
        //开始查询 传入条件和pageable对象
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        List<Hospital> hospitalList = pages.getContent();
        //远程调用封装
        hospitalList.stream().forEach(item->{
            this.setHospitalHosType(item);
        });

        return pages;
    }

    /**
     * 使用远程调用查询字典 封装医院名称和地区
     * @param hospital
     * @return
     */
    private Hospital setHospitalHosType(Hospital hospital){
        //通过valus获取医院名称 这里hospital.getHostype()就是value
        String hospName = dictFeignClient.getName("Hostype",hospital.getHostype());
        //查询省、市、区
        String provinceName = dictFeignClient.getName(hospital.getProvinceCode());
        String cityName = dictFeignClient.getName(hospital.getCityCode());
        String districtName = dictFeignClient.getName(hospital.getDistrictCode());

        hospital.getParam().put("hostypeString",hospName);
        hospital.getParam().put("fullAddress",provinceName+cityName+districtName);


        return hospital;
    }


    /**
     * 更新医院状态
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            //先通过id查询
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 通过id查询医院信息
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> getHospById(String id) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.setHospitalHosType(hospitalRepository.findById(id).get());
        //医院基本信息 包含医院等级
        result.put("hospital", hospital);

        //单独处理更直观  预约信息
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);

        return result;

    }

    /**
     * 通过医院名称模糊查询医院值
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findHospByName(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.setHospitalHosType(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }


}
